﻿using System;

namespace DotNetCommon.Validate.Annotations;

/// <summary>
/// 字符串必须是GUID格式的, 示例:
/// <code>
/// [VMustGuid("N")]
/// public string UserGuid { get; set; }
/// </code>
/// </summary>
/// <remarks>
/// 注意: <br />
/// <c>format</c> 参数用以限制GUID的格式(空值表示不限定格式), 比如:
/// <list type="bullet">
/// <item>"N": "cd5abdcde9ce44d6bca48f5a8fda2e95"</item>
/// <item>"D": "cd5abdcd-e9ce-44d6-bca4-8f5a8fda2e95"</item>
/// <item>"B": "{cd5abdcd-e9ce-44d6-bca4-8f5a8fda2e95}"</item>
/// <item>"P": "(cd5abdcd-e9ce-44d6-bca4-8f5a8fda2e95)"</item>
/// <item>"X": "{0xcd5abdcd,0xe9ce,0x44d6,{0xbc,0xa4,0x8f,0x5a,0x8f,0xda,0x2e,0x95}}"</item>
/// </list>
/// 另外: 
/// <list type="bullet">
/// <item>当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</item>
/// <item>默认字符串不能为 null, 如果允许字符串为 null, 使用 [VMustGuid(canBeNull:true)] </item>
/// </list>
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMustGuidAttribute(string format = null, bool ignoreCase = false, string errorMessage = null) : Attribute, IValidateAction
{
    public string Format { get; } = format;
    public bool IgnoreCase { get; } = ignoreCase;
    public string ErrorMessage { get; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        ValidateStringExtensions.MustBeGuidInternal(ctx, ctx.ModelValue?.ToString(), Format, IgnoreCase, ErrorMessage);
    }
}

/// <summary>
/// 如果不为null, 则字符串必须是GUID格式的, 示例:
/// <code>
/// [VMustGuidIfNotNull("N")]
/// public string UserGuid { get; set; }
/// </code>
/// </summary>
/// <remarks>
/// 注意: <br />
/// <c>format</c> 参数用以限制GUID的格式(空值表示不限定格式), 比如:
/// <list type="bullet">
/// <item>"N": "cd5abdcde9ce44d6bca48f5a8fda2e95"</item>
/// <item>"D": "cd5abdcd-e9ce-44d6-bca4-8f5a8fda2e95"</item>
/// <item>"B": "{cd5abdcd-e9ce-44d6-bca4-8f5a8fda2e95}"</item>
/// <item>"P": "(cd5abdcd-e9ce-44d6-bca4-8f5a8fda2e95)"</item>
/// <item>"X": "{0xcd5abdcd,0xe9ce,0x44d6,{0xbc,0xa4,0x8f,0x5a,0x8f,0xda,0x2e,0x95}}"</item>
/// </list>
/// 另外: 
/// <list type="bullet">
/// <item>当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</item>
/// <item>默认字符串不能为 null, 如果允许字符串为 null, 使用 [VMustGuid(canBeNull:true)] </item>
/// </list>
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMustGuidIfNotNullAttribute(string format = null, bool ignoreCase = false, string errorMessage = null) : Attribute, IValidateAction
{
    public string Format { get; } = format;
    public bool IgnoreCase { get; } = ignoreCase;
    public string ErrorMessage { get; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        if (ctx.ModelValue == null) return;
        ValidateStringExtensions.MustBeGuidInternal(ctx, ctx.ModelValue?.ToString(), Format, IgnoreCase, ErrorMessage);
    }
}
